pub mod dept;
pub mod resource;
pub mod role;
pub mod sys_dict;
pub mod sys_log;
pub mod user;
use sea_orm::ConnectionTrait;
pub use {dept::*, resource::*, role::*, sys_dict::*, sys_log::*, user::*};

pub(crate) type Result<T> = std::result::Result<T, sea_orm::DbErr>;

pub struct DeptFilter(i32, Option<String>);

impl DeptFilter {
    pub fn new(id: i32) -> Self {
        Self(id, None)
    }

    pub fn new_ancestors(id: i32, ancestor: String) -> Self {
        Self(id, Some(ancestor))
    }

    pub async fn new_with_child(id: i32, db: &impl ConnectionTrait) -> Result<Option<Self>> {
        Ok(
            if let Some(dept) = dept::Dept::get_by_id::<Dept2Vo>(db, id, None, Some(false)).await? {
                Some(Self(
                    id,
                    Some(format!("{}{}/", dept.ancestors, dept.dept_id)),
                ))
            } else {
                None
            },
        )
    }

    pub fn into_condition(self) -> sea_orm::Condition {
        use sea_orm::ColumnTrait;
        sea_orm::Condition::any()
            .add(crate::entity::sys_dept::Column::DeptId.eq(self.0))
            .add_option(
                self.1
                    .map(|a| crate::entity::sys_dept::Column::Ancestors.starts_with(a)),
            )
    }
}
